<div class="layui-card">
    <div class="layui-card-header">
        <h2 class="header-title">应用管理</h2>
        <span class="layui-breadcrumb pull-right">
          <a href="#!home_console">首页</a>
          <a><cite>应用管理</cite></a>
        </span>
    </div>
    <div class="layui-card-body">
        <div class="layui-form toolbar">
        搜索：<input id="app-edit-search" class="layui-input search-input" type="text" placeholder="输入关键字"/>&emsp;
        <button id="app-btn-search" class="layui-btn icon-btn"><i class="layui-icon">&#xe615;</i>搜索</button>
        <button id="app-btn-add" class="layui-btn icon-btn"><i class="layui-icon">&#xe654;</i>添加</button>
        </div>

        <!-- 数据表格 -->
        <table class="layui-table" id="app-table" lay-filter="app-table"></table>
    </div>
</div>

<!-- 表格状态列 -->
<script type="text/html" id="client-tpl-state">
    <input type="checkbox" lay-filter="client-tpl-state" value="{{d.id}}" lay-skin="switch" lay-text="正常|锁定"
            {{d.status==true?'checked':''}}/>
</script>

<!-- 表格操作列 -->
<script type="text/html" id="app-table-bar">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    <a class="layui-btn layui-btn-xs" lay-event="services">服务管理</a>
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="app-model">
    <form id="app-form" lay-filter="app-form" class="layui-form model-form">
        <input name="id" type="hidden"/>
        <div class="layui-form-item">
            <label class="layui-form-label">应用标识</label>
            <div class="layui-input-block">
                <input name="clientId" placeholder="请输入应用标识" type="text" class="layui-input" maxlength="20"
                       lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">应用密钥</label>
            <div class="layui-input-block">
                <input name="clientSecretStr" placeholder="请输入应用密钥" type="text" class="layui-input" maxlength="20"
                       lay-verify="required" required />
            </div>
        </div>
         <div class="layui-form-item">
            <label class="layui-form-label">回调地址</label>
            <div class="layui-input-block">
                <input name="webServerRedirectUri" placeholder="请输入回调地址" type="text" class="layui-input" maxlength="100"
                       lay-verify="required" required />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">是否限流</label>
            
            <div class="layui-input-block">
                <input type="radio" name="ifLimit" value="0" title="否" checked/>
            	<input type="radio" name="ifLimit" value="1" title="是"/>
            </div>
            
           
        </div>
        
        <div class="layui-form-item">
	        <label class="layui-form-label">限流次数</label>
	        <div class="layui-input-block">
	            <input name="limitCount" placeholder="请输入限流次数" type="number" class="layui-input" lay-verify="required" value="10000" required/>
	        </div>
   		 </div>
        
        <div class="layui-form-item">
            <label class="layui-form-label">授权模式</label>
            <div class="layui-input-block">
            	<input type="checkbox" name="authorizedGrantTypes" lay-skin="primary" title="简化模式" value="implicit" checked>
            	<input type="checkbox" name="authorizedGrantTypes" lay-skin="primary" title="客户端模式" value="client_credentials" checked>
                <input type="checkbox" name="authorizedGrantTypes" lay-skin="primary" title="密码模式" value="password" checked>
                <input type="checkbox" name="authorizedGrantTypes" lay-skin="primary" title="授权码模式" value="authorization_code" checked>
                <input type="checkbox" name="authorizedGrantTypes" lay-skin="primary" title="刷新令牌模式" value="refresh_token" checked>
                <input type="checkbox" name="authorizedGrantTypes" lay-skin="primary" title="手机短信模式" value="mobile" checked>
            </div>
        </div>
        
        <div class="layui-form-item model-form-footer">
            <button class="layui-btn layui-btn-primary" ew-event="closeDialog" type="button">取消</button>
            <button class="layui-btn" lay-filter="app-form-submit" lay-submit>保存</button>
        </div>
    </form>
</script>


<script>
    layui.use(['form', 'table', 'util', 'config', 'admin'],function () {
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var layer = layui.layer;
        var util = layui.util;
        var admin = layui.admin;


        // 渲染表格
        table.render({
            elem: '#app-table',
            url: config.base_server + 'api-auth/clients',
            method: 'GET',
            where: {
                access_token: config.getToken().access_token
            },
            page: true,
            cols: [[
                {type: 'numbers'},
                {field: 'clientId', sort: true, title: '应用标识'},
                {field: 'clientSecretStr',  sort: true, title: '应用密钥'},
                {field: 'webServerRedirectUri',sort: true, title: '回调地址'},
                {field: 'authorizedGrantTypes', width:320 ,sort: true, title: '授权方式'},
                {field: 'ifLimit',sort: true, title: '是否限流'},
                {field: 'limitCount'  ,sort: true, title: '每日API可访问次数'},
                {field: 'enabled', sort: true, templet: '#client-tpl-state', title: '状态',width: 150},
                {align: 'center',width:250, toolbar: '#app-table-bar', title: '操作'}
            ]]
        });

        // 工具条点击事件
        table.on('tool(app-table)', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;

            if (layEvent === 'del') { // 删除
                doDelete(obj);
            }else if (layEvent === 'edit'){ //修改
                showEditModel(data);
            }else if(layEvent == 'services'){   //服务管理
                showServicesDialog(obj.data.id);
            }
        });


        // 删除
        var doDelete = function (obj) {
            layer.confirm('确定要删除吗？', function (i) {
                layer.close(i);
                layer.load(2);
                admin.req('api-auth/clients/' + obj.data.id, {}, function (data) {
                    layer.closeAll('loading');
                    layer.msg('成功', {icon: 1, time: 500});
                    obj.del();
                }, 'DELETE');
            });
        };

        // 搜索按钮点击事件
        $('#app-btn-search').click(function () {
            var key = $('#app-edit-search').val();
            table.reload('app-table', {where: {searchKey: key}});
        });

        // 添加按钮点击事件
        $('#app-btn-add').click(function () {
            showEditModel();
        });


        // 显示编辑弹窗
        var showEditModel = function (data) {
        	debugger;
            layer.open({
                type: 1,
                title: data ? '修改应用' : '添加应用',
                area: '450px',
                offset: '120px',
                content: $('#app-model').html(),
                success: function () {
                    $('#app-form')[0].reset();
                    $('#app-form').attr('method', 'POST');
                    if (data) {
                    	//禁用修改clientId
                        $("input[name='clientId']").attr('disabled',true);
                        $("input[name='clientId']").attr('class',"layui-input layui-disabled");
                        form.val('app-form', data);
                       
						let authorizedGrantTypesArr = data.authorizedGrantTypes.split(",");
                        $('input[type=checkbox][name=authorizedGrantTypes]').each(function() {
                            let typeValue = $(this).val();
                            let isCheck = false;
                            for (var i = 0; i < authorizedGrantTypesArr.length; i++) {
                                if (typeValue === authorizedGrantTypesArr[i]) {
                                    isCheck = true;
                                    break;
                                }
                            }
                            $(this).prop("checked", isCheck);
                        });
                        let ifLimitStr = data.ifLimit +'';
                         $('input[type=radio][name=ifLimit').each(function() {
                            let typeValue = $(this).val();
                            let isCheck = false;
                            if (typeValue ===  ifLimitStr ) {
                                    isCheck = true;
                            }
                            $(this).prop("checked", isCheck);
                        });
                        
                    }
                }
            });
        };

        // 表单提交事件
        form.on('submit(app-form-submit)', function (data) {
        	
			let authorizedGrantTypesArr = [];
            $('input[type=checkbox][name=authorizedGrantTypes]:checked').each(function() {
                authorizedGrantTypesArr.push($(this).val());
            });
            data.field.authorizedGrantTypes = authorizedGrantTypesArr.join(",");
            layer.load(2);
            admin.req('api-auth/clients/saveOrUpdate', JSON.stringify(data.field), function (data) {
                layer.closeAll('loading');
                console.log(data);
                if (data.code == 0) {
                    layer.msg(data.msg, {icon: 1, time: 500});
                    table.reload('app-table');
                    layer.closeAll('page');
                } else {
                    layer.msg(data.msg, {icon: 2, time: 500});
                }
            }, $('#app-form').attr('method'));
            return false;
        });

		// 修改应用状态
        form.on('switch(client-tpl-state)', function (obj) {
        	debugger ;
        	var reqData = {
                id: obj.elem.value,
                status: obj.elem.checked ? true : false
            } ;
            layer.load(2);
            admin.req('api-auth/clients/updateEnabled',JSON.stringify(reqData) , function (data) {
                layer.closeAll('loading');
                if (data.code == 0) {
                    layer.msg(data.msg, {icon: 1, time: 500});
                    //table.reload('table-user', {});
                } else {
                    layer.msg(data.msg, {icon: 2, time: 500});
                    $(obj.elem).prop('checked', !obj.elem.checked);
                    form.render('checkbox');
                }
            }, 'PUT');
        });


        // 服务管理
        var showServicesDialog = function (clientId) {
            layer.open({
                type: 1,
                title: '服务管理',
                area: ['600px', '500px'],
                offset: '120px',
                content: '<ul id="treeServices" class="ztree" style="padding: 25px 0px 20px 60px;"></ul>',
                btn: ['保存', '关闭'],
                btnAlign: 'c',
                success: function (layero, index) {
                    $(layero).children('.layui-layer-content').css('overflow-y', 'auto');
                    layer.load(2);
                    var setting = {
                        check: {enable: true},
                        data: {
                            simpleData: {
                                enable: true
                            }
                        }
                    };
                    admin.req('api-auth/services/'+clientId+'/services', {}, function (data) {
                        $.fn.zTree.init($('#treeServices'), setting, data);
                        layer.closeAll('loading');
                    }, 'GET');

                },
                yes: function (index) {
                    layer.load(1);
                    var treeObj = $.fn.zTree.getZTreeObj('treeServices');
                    var nodes = treeObj.getCheckedNodes(true);
                    var ids = new Array();
                    for (var i = 0; i < nodes.length; i++) {
                        ids[i] = nodes[i].id;
                    }
                    var data = new Object();
                    data.id = clientId;
                    data.serviceIds = ids;

                    admin.req('api-auth/services/granted', JSON.stringify(data) , function (data) {
                        layer.closeAll('loading');
                        if (0 == data.code) {
                            layer.msg(data.msg, {icon: 1, time: 500});
                            layer.close(index);
                        } else {
                            layer.msg(data.msg, {icon: 2, time: 500});
                        }
                    }, 'POST');
                }
            });
        }

    });
</script>